//
//  JkmMainTabBarController.swift
//  SinaWb
//
//  Created by Jiang on 16/5/8.
//  Copyright © 2016年 Jiang. All rights reserved.
//

import UIKit

//super.init() 时会调用viewload 和viewdidload
class JkmMainTabBarController: UITabBarController {
    var imageArray : Array<String>?
    var TitleArray : Array<String>?
    var controllerArray :Array <String>?
    
    //MARK: - Compose按钮监听
    @objc  private func clickComposeButton() {
        JkLog("")
    }

    //MARK: - 扩展init方法
      init(imageArray : Array<String>, TitleArray :Array<String> ,controllerArray: Array<String>){
        
        self.imageArray = imageArray
        
        self.TitleArray = TitleArray
        
        var  controllers : Array<String> = Array()
        
        for str in controllerArray{
            
            controllers.append(str)
        }
        
        
        self.controllerArray = controllers
        
        super.init(nibName: nil, bundle: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    
    //MARK: - 添加所有的控制器
    private func AddAllChildViewController() {

        for  i in 0  ..< Int((TitleArray?.count)!){
            
            SetTheTabBarItemOfController(TabBarController: controllerArray![i],
                                         ImageName: imageArray![i] ,
                                         title: TitleArray![i])

        }
        
    }
    private func SetTheTabBarItemOfController(TabBarController controller : String ,
                                                               ImageName : String,
                                                               title : String){
        // 获取命名空间名称
        let ProductName = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        
        let clas :UIViewController.Type = NSClassFromString(ProductName + "." + controller) as! UIViewController.Type
        
        let  con = clas.init()
        
        let nav = UINavigationController(rootViewController: con)
        
  
        con.tabBarItem.image = UIImage(named: ImageName)
        
        
        con.title = title
        
        addChildViewController(nav)
        
    }
    
    //MARK: - viewDidLoad 和 viewWillAppear
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        let jkmtabbar = JkmTabBar() //使用自定义的TabBar
        
        setValue(jkmtabbar, forKeyPath: "tabBar")
        
        jkmtabbar.composeButton.addTarget(self, action: #selector(clickComposeButton), forControlEvents: UIControlEvents.TouchUpInside)
        
        AddAllChildViewController()
        
    }
}
